import { createRouter, createWebHistory } from "vue-router";
import HomeView from "../views/home/HomeView.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      component: HomeView,
    },
    {
      path: "/home",
      name: "home",
      component: HomeView,
    },
    {
      path: "/login",
      name: "login",
      component: () => import("../views/login/LoginView.vue"),
    },
    {
      path: "/register",
      name: "register",
      component: () => import("../views/login/RegisterView.vue"),
    },
    {
      path: "/resetPassword",
      name: "resetPassword",
      component: () => import("../views/login/ResetpassView.vue"),
    },
  ],
});

// 全局导航
router.beforeEach((to, from, next) => {
  var auth = localStorage.getItem("token");
  if (
    to.path == "/login" ||
    to.path == "/register" ||
    to.path == "/resetPassword"
  ) {
    if (auth) {
      router.push("/home");
    } else {
      next();
    }
  } else {
    if (auth) {
      next();
    } else {
      router.push("/login");
    }
  }
});

export default router;
